package com.panda.expand;

import com.panda.pojo.Block;
import com.panda.pojo.Context;
import com.panda.pojo.Element;
import com.panda.pojo.StringBlock;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TransformElementSugar extends ElementSugar {

    //清空所有后续处理
    @Override
    public String parseBody(Context context, Element element, String s) {

        if (element instanceof Transform) {
            return "";
        }

        return s;

    }

    @Override
    public boolean canParse(String s, Context context) {
        return s.equals("Transform");
    }

    @Override
    protected Element makeElement(String e, Context context) {
        return new Transform(context, e);
    }

    private static class Transform extends Element {

        Transform(Context context, String name) {
            super(context, name);
        }


        @Override
        public void addSubBlock(Block block) {

            throw new RuntimeException("Transform中不能添加子元素");

        }

        @Override
        public String toString() {


            String s = getBodyText();

            StringBuilder builder = new StringBuilder();

            Matcher matcher = pattern.matcher(s);

            Map<String, String> stringMap = context.getStringMap();

            //找到根元素,将自己的属性追加给该元素
            if (matcher.find()) {

                builder.delete(0, builder.length());

                attributes.forEach((k, v) -> {

                    if (v == null) {
                        builder.append(" ").append(k);
                    } else {

                        //交给组件自行展开
                        if (stringMap.containsKey(v) || v.startsWith("__string_temp_")) {
                            builder.append(" ").append(k).append("=").append(v);
                        } else {
                            builder.append(" ").append(k).append("=").append("\"").append(v).append("\"");
                        }

                    }


                });

                String group = matcher.group();
                s = s.replaceFirst(group, group + builder.toString());

                return s;
            }

            throw new RuntimeException("未找到有效标签");

        }

        private static Pattern pattern = Pattern.compile("^[ \n]*<[a-zA-Z0-9]+");


    }


}
